<template>
  <div class="edit-restaurant">
    <h2>编辑餐厅信息</h2>
    <form @submit.prevent="submitForm">
      <label for="name">名称:</label>
      <input type="text" id="name" v-model="restaurantData.name" required />

      <label for="address">地址:</label>
      <input type="text" id="address" v-model="restaurantData.address" />

      <label for="phone">电话:</label>
      <input type="text" id="phone" v-model="restaurantData.phone" />

      <label for="openinghours">营业时间:</label>
      <input type="text" id="openinghours" v-model="restaurantData.openinghours" />

      <label for="rating">餐厅评分:</label>
      <input
          type="text"
          id="rating"
          v-model="restaurantData.rating"
          @input="validateRating"
          placeholder="请输入有效的评分（如 4.5）"
      />

      <label for="type">餐厅类型:</label>
      <input type="text" id="type" v-model="restaurantData.type" />

      <button type="submit">保存修改</button>
    </form>
  </div>
</template>


<script>
export default {
  name: 'EditRestaurant',
  data() {
    return {
      restaurantId: null,
      restaurantData: {} // 存储查询到的数据
    };
  },
  created() {
    this.restaurantId = this.$route.params.id;
    this.fetchRestaurantData();
  },
  methods: {
    async fetchRestaurantData() {
      try {
        // 假设调用 API 查询数据，例如：

        const url = `http://localhost:8090/restaurants/selectOneRestaurants`;
        const params = new URLSearchParams({
          id: this.restaurantId
        });
        fetch(`${url}?${params.toString()}`)
            .then(response => response.json())
            .then(json => {
              console.log(json);
              this.restaurantData = json.data;
            });
      } catch (error) {
        console.error('获取餐厅数据失败:', error);
      }
    },
    async submitForm() {
      try {
        const url = `http://localhost:8090/restaurants/updateRestaurants`;
        const response = await fetch(url, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({
            id: this.restaurantId,
            ...this.restaurantData
          })
        });

        const result = await response.json();
        if (result.code === 200) {
          alert('保存成功');
          this.$router.push('/');
          this.$root.$emit('refresh-data');
        }
      } catch (error) {
        console.error('请求出错:', error);
        alert('网络错误，请重试');
      }
    },
    validateRating() {
      // 使用正则替换非数字和小数点的内容，并限制最多一位小数
      const value = this.restaurantData.rating;
      const formattedValue = value.replace(/[^0-9.]/g, '') // 移除非数字和非小数点字符
          .replace(/(\..*)\./g, '$1') // 防止多个小数点
          .replace(/^(\d+)(\.\d{0,1})?.*$/, '$1$2'); // 保留最多一位小数

      // 如果输入无效，则提示用户
      if (formattedValue && (formattedValue < 0 || formattedValue > 5)) {
        alert('评分必须在 0 到 5 之间，且最多一位小数！');
        this.restaurantData.rating = ''; // 清空输入
        return;
      }

      this.restaurantData.rating = formattedValue; // 更新为格式化后的值
    }
  }
};
</script>
<style scoped>
.edit-restaurant {
  max-width: 600px;
  margin: 0 auto;
  padding: 20px;
}

form {
  display: flex;
  flex-direction: column;
}

label {
  margin-top: 10px;
  font-weight: bold;
}

input {
  padding: 8px;
  margin-top: 5px;
  border: 1px solid #ccc;
  border-radius: 4px;
}

button {
  margin-top: 20px;
  padding: 10px;
  background-color: #42b983;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}
</style>


